package com.hmyd.hmyd_android.ui;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.commons.Constants;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dialog.ConfirmInvestmentDialog;
import com.hmyd.hmyd_android.dialog.InvestmentSuccessDialog;
import com.hmyd.hmyd_android.dialog.NormalDialog;
import com.hmyd.hmyd_android.dialog.NormalDialogListener;
import com.hmyd.hmyd_android.dto.AvailableAmountOfHmwallet;
import com.hmyd.hmyd_android.dto.Capital;
import com.hmyd.hmyd_android.dto.Coupon;
import com.hmyd.hmyd_android.dto.CouponGroup;
import com.hmyd.hmyd_android.dto.InterestTime;
import com.hmyd.hmyd_android.dto.Score;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.PreferencesUtils;
import com.hmyd.hmyd_android.utils.Utils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.shangzhu.apptrack.AppTrack_2423;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;

/**
 * 票惠宝（T+30）——确认
 * 
 * @author wangc
 * 
 */

@ContentView(R.layout.activity_tickets30_confirm)
public class TicketsWithCouponConfirmActivity extends BasicActivity {

	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;

	@ViewInject(R.id.investment_name)
	private TextView investment_name;
	@ViewInject(R.id.investment_rate)
	private TextView investment_rate;
	@ViewInject(R.id.investment_time)
	private TextView investment_time;

	@ViewInject(R.id.personal_name)
	private TextView personal_name;
	@ViewInject(R.id.personal_tel)
	private TextView personal_tel;

	@ViewInject(R.id.investAmount)
	private EditText mInvestAmountEditText;
	@ViewInject(R.id.confirm_investment)
	private Button mConfirmInvestment;

	@ViewInject(R.id.interestReceive)
	private TextView interestReceive;
	@ViewInject(R.id.interestStart)
	private TextView interestStart;

	@ViewInject(R.id.enable_amount)
	private TextView enable_amount;
	@ViewInject(R.id.amount_expected)
	private TextView amount_expected;
	@ViewInject(R.id.amount_score)
	private TextView amount_score;
	@ViewInject(R.id.xiao_hui)
	private TextView xiao_hui;
	@ViewInject(R.id.xiao_hui_switch)
	private ImageView xiao_hui_switch;

	private CouponGroup mCouponGroup;
	@ViewInject(R.id.coupon_item_layout)
	private TableLayout mCouponItemLayout;
	@ViewInject(R.id.assets_coupons)
	private TextView mAssetsCoupons;
	@ViewInject(R.id.assets_coupons_more)
	private ImageView assets_coupons_more;

	// Bottom
	@ViewInject(R.id.pay_account)
	private TextView pay_account;
	@ViewInject(R.id.pay_amount)
	private TextView pay_amount;

	private final int BILL_TIME = 6;// 收益时间
	private final int AVAILABLE_AMOUNT = 7;// 预期每日收益

	private final int GETCOUPONBYITEM = 1;// 项目可用现金券
	private final int CAPITAL = 2;// 资产明细
	private final int SUBMIT = 3;// 确认投资
	private final int CONVER = 4;// 积分换算
	private final int AVAILABLEAMOUNTOFHMWALLET = 5;// 计算可获小惠钱包

	private Capital mCapital;
	private InterestTime interestTime;
	private String mId;
	private double mMount;

	private String mBaseAmount;
	private String mMinInvestAmount;

	private double mHMWallet = 0.00;

	private HashMap<String, String> couponMap = new HashMap<String, String>();
	// 使用情况
	HashMap<String, Object> used = new HashMap<String, Object>();
	// 现金券总额
	private double couponsAmount;

	public static Intent getIntent(Context context, String id, String type, String name,
			String rate, String time, String timeUnit, double mount, long endTime,
			String itemStatus, String baseAmount, String minInvestAmount, String totalAmount,
			String purchasedAmount, String itemRateId, String dailyMInterest) {
		Intent intent = new Intent(context, TicketsWithCouponConfirmActivity.class);
		intent.putExtra("id", id);
		intent.putExtra("type", type);
		intent.putExtra("name", name);
		intent.putExtra("rate", rate);
		intent.putExtra("time", time);
		intent.putExtra("timeUnit", timeUnit);
		intent.putExtra("mount", mount);
		intent.putExtra("endTime", endTime);
		intent.putExtra("itemStatus", itemStatus);

		intent.putExtra("baseAmount", baseAmount);
		intent.putExtra("minInvestAmount", minInvestAmount);

		intent.putExtra("totalAmount", totalAmount);
		intent.putExtra("purchasedAmount", purchasedAmount);
		intent.putExtra("itemRateId", itemRateId);
		intent.putExtra("dailyMInterest", dailyMInterest);

		return intent;
	}

	@OnClick({ R.id.confirm_investment, R.id.xiao_hui_switch, R.id.assets_coupons_more,
			R.id.back_info })
	public void onClick(View v) {
		Message message = new Message();
		String mInvestAmount = mInvestAmountEditText.getText().toString().trim();

		if (TextUtils.isEmpty(mInvestAmount)) {
			MyToast.showHMToast(this, false, "请输入投资金额");
		} else if (mCapital != null
				&& Double.parseDouble(mInvestAmount) > mCapital.availableBalance) {
			message.what = 5;
			verificationHandler.sendMessage(message);
		} else if (v.getId() == R.id.confirm_investment) {
			if (isFastDoubleClick()) {
				return;
			}

			if (caculateAccount() < 0) {
				MyToast.showHMToast(this, false, "实际投资金额过小！");
				return;
			}
			
			message.what = 7;
			verificationHandler.sendMessage(message);
			

			/*RequestParams params = new RequestParams();
			params.addBodyParameter("itemId", mId);
			params.addBodyParameter("investAmount", String.valueOf(mMount));
			params.addBodyParameter("itemRateId", getIntent().getStringExtra("itemRateId"));

			if (String.valueOf(xiao_hui_switch.getTag()).equals("on")) {
				params.addBodyParameter("useWalletAmount", String.valueOf(xiao_hui.getTag()));
			} else {
				params.addBodyParameter("useWalletAmount", String.valueOf(0));
			}

			StringBuilder builder = new StringBuilder();
			if (String.valueOf(assets_coupons_more.getTag()).equals("on")) {
				if (couponMap.size() > 0) {
					for (HashMap.Entry<String, String> entry : couponMap.entrySet()) {
						System.out.println(entry.getKey() + "--->" + entry.getValue());
						params.addBodyParameter("couponIds", entry.getValue());
						builder.append(entry.getValue()+",");
					}
				}
			}
			
			params.addBodyParameter("couponsAmount", String.valueOf(couponsAmount));

//			mConfirmInvestment.setEnabled(false);
			mConfirmInvestment.setText("提交中...");
			setSubmitColor(false);

			onRequest(SUBMIT, UrlConstant.BILL_INVESTMENT, HttpMethod.POST, params);
			//加入99统计，统计投资点击次数，使用现金券id
			AppTrack_2423.countClick(Constants.ConfirmInvestmentPageTopic, "投资次数_票惠宝", "ozsru="+AppBasic.username, builder.toString());*/
		} else if (v.getId() == R.id.xiao_hui_switch) {
			double mhWallet = 0;
			String xiaohuiSwithc = "";
			if (String.valueOf(xiao_hui_switch.getTag()).equals("off")) {
				// 有可使用的小惠钱包
				if (xiao_hui.getTag() != null
						&& !TextUtils.isEmpty(String.valueOf(xiao_hui.getTag()))
						&& Double.parseDouble(String.valueOf(xiao_hui.getTag())) > 0) {
					mhWallet = Double.parseDouble(xiao_hui.getTag().toString());

					xiao_hui_switch.setTag("on");
					xiao_hui_switch.setImageResource(R.drawable.an_kg_on);

					getAvailableAmountOfHmwallet();// 计算可获小惠钱包
					xiaohuiSwithc = "on";
				}
			} else if (String.valueOf(xiao_hui_switch.getTag()).equals("on")) {
				xiao_hui_switch.setImageResource(R.drawable.an_kg_off);
				xiao_hui_switch.setTag("off");
				xiaohuiSwithc = "off";
				getAvailableAmountOfHmwallet();// 计算可获小惠钱包
			}
			//加入99统计，统计小惠钱包使用
			AppTrack_2423.countClick(Constants.ConfirmInvestmentPageTopic, "小惠钱包_票惠宝", "ozsru="+AppBasic.username, xiaohuiSwithc+xiao_hui.getText());
			if (mhWallet > 0 && xiao_hui_switch.getTag().equals("on")) {
				xiao_hui.setText(mHMWallet + "  已抵用" + mhWallet);

				used.put("Wallet", mhWallet);
			} else {
				xiao_hui.setText(mHMWallet + "");
				if (used.containsKey("Wallet")) {
					used.remove("Wallet");
				}
			}

			// caculateAccount();
		} else if (v.getId() == R.id.assets_coupons_more) {
			String couponSwitch = "";
			if (String.valueOf(assets_coupons_more.getTag()).equals("off")) {
				if (mCouponGroup != null && mCouponGroup.couponList.size() > 0) {
					MyToast.showHMToast(this, false, "您未选中现金券，请点击选中！");
					assets_coupons_more.setTag("on");
					assets_coupons_more.setImageResource(R.drawable.an_kg_on);

					mCouponItemLayout.setVisibility(View.VISIBLE);

					drawCouponGroup(mCouponGroup);
					couponSwitch = "on";
				}
			} else if (String.valueOf(assets_coupons_more.getTag()).equals("on")) {
				resetCouponsParams();
				caculateAccount();
				couponSwitch = "off";
			}
			//加入99统计，统计是否开启现金券
			AppTrack_2423.countClick(Constants.ConfirmInvestmentPageTopic, "现金券_票惠宝", "ozsru="+AppBasic.username, couponSwitch);
			// caculateAccount();
		} else if (v.getId() == R.id.back_info) {

			Utils.jumpURL(TicketsWithCouponConfirmActivity.this, AppBasic.app.billLinkUrl, "赎回说明",
					"", false);
		}
	}

	int couponGroupNum = 0;// 一共有几张可以用的
	double couponGroupSelected = 0;// 选择券的总金额
	double requiredMinSelected = 0;// 选择券的总最低起投金额
	private List<Coupon> tempCoupon = new ArrayList<Coupon>();

	/**
	 * 创建优惠券
	 * 
	 * @param couponGroup
	 */
	private void drawCouponGroup(final CouponGroup couponGroup) {
		tempCoupon.clear();
		mCouponItemLayout.removeAllViews();
		LayoutInflater mInflater = LayoutInflater.from(this);

		View viewConfirmCouponItem = null;

		couponGroupNum = 0;// 一共有几张可以用的
		couponGroupSelected = 0;// 选择券的总金额
		requiredMinSelected = 0;// 选择券的总最低起投金额
		couponMap.clear();

		final List<List<Coupon>> lists = getCouponGroup(couponGroup.couponList);

		for (int i = 0; i < lists.size(); i++) {
			final List<Coupon> couponList = lists.get(i);
			TextView minInvestValueView = new TextView(this);
			minInvestValueView.setText("起投金额    " + couponList.get(0).requiredMinInvestValue
					+ "元以上");
			minInvestValueView.setTextColor(getResources().getColor(R.color.black));
			minInvestValueView.setTextSize(12);
			minInvestValueView.setPadding(0, 15, 0, 0);

			mCouponItemLayout.addView(minInvestValueView);

			for (int j = 0; j < couponList.size(); j++) {
				couponGroupNum++;

				final Coupon coupon = couponList.get(j);

				if (j % 2 == 0) {
					viewConfirmCouponItem = mInflater.inflate(R.layout.view_confirm_coupon_item,
							null);
					final RelativeLayout leftCouponLayout = (RelativeLayout) viewConfirmCouponItem
							.findViewById(R.id.left_coupon_layout);
					leftCouponLayout.setVisibility(View.VISIBLE);

					final ImageView leftCouponBg = (ImageView) leftCouponLayout
							.findViewById(R.id.left_coupon_bg);

					final TextView leftCouponTitle = (TextView) leftCouponLayout
							.findViewById(R.id.left_coupon_title);
					leftCouponTitle.setText(coupon.channelTitle);

					final TextView leftCouponNum = (TextView) leftCouponLayout
							.findViewById(R.id.left_coupon_num);
					leftCouponNum.setText(Utils.amountConversionFormat(coupon.nominalValue));

					final TextView leftCouponUnit = (TextView) leftCouponLayout
							.findViewById(R.id.left_coupon_unit);

					final TextView leftCouponTime = (TextView) leftCouponLayout
							.findViewById(R.id.left_coupon_time);
					leftCouponTime.setText("过期时间：" + Utils.getDateString(coupon.expTime));

					leftCouponLayout.setTag(R.id.tag_first, "unSelected");
					leftCouponLayout.setTag(R.id.tag_second, "left"
							+ couponList.get(0).requiredMinInvestValue + j);
					leftCouponLayout.setTag(R.id.tag_third, j);
					leftCouponLayout.setTag(R.id.tag_fourth, i);

					if (coupon.requiredMinInvestValue > mMount) {
						leftCouponBg.setImageResource(R.drawable.que_img_hui);
						leftCouponTitle.setTextColor(getResources().getColor(R.color.white));
						leftCouponNum.setTextColor(getResources().getColor(R.color.white));
						leftCouponUnit.setTextColor(getResources().getColor(R.color.white));
						leftCouponTime.setTextColor(getResources().getColor(R.color.white));
					} else {
						leftCouponBg.setImageResource(R.drawable.que_img_bai);
						leftCouponTitle.setTextColor(getResources().getColor(R.color.text_orange));
						leftCouponNum.setTextColor(getResources().getColor(R.color.text_orange));
						leftCouponUnit.setTextColor(getResources().getColor(R.color.text_orange));
						leftCouponTime.setTextColor(getResources().getColor(R.color.text_orange));
					}

					leftCouponLayout.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {

							if (coupon.requiredMinInvestValue > mMount) {
								MyToast.showHMToast(TicketsWithCouponConfirmActivity.this, false,
										"起投金额最低" + coupon.requiredMinInvestValue + "可用！");
								return;
							}

							if ("selected".equals(String.valueOf(leftCouponLayout
									.getTag(R.id.tag_first)))) {
								couponGroupSelected = couponGroupSelected - coupon.nominalValue;
								requiredMinSelected = requiredMinSelected
										- coupon.requiredMinInvestValue;

								couponMap.remove(String.valueOf(leftCouponLayout
										.getTag(R.id.tag_second)));

								couponSelectedStyle(leftCouponBg, leftCouponTitle, leftCouponNum,
										leftCouponUnit, leftCouponTime);
								leftCouponLayout.setTag(R.id.tag_first, "unSelected");
							} else {
								/* 计算投资金额数目 start */
								requiredMinSelected = requiredMinSelected
										+ coupon.requiredMinInvestValue;
								if (mMount - requiredMinSelected < 0) {
									requiredMinSelected = requiredMinSelected
											- coupon.requiredMinInvestValue;

									MyToast.showHMToast(TicketsWithCouponConfirmActivity.this,
											false, "投资金额不足以可用！");
									return;
								}
								/* 计算投资金额数目 end */

								if ("multiple".equals(couponGroup.type)) {// 多选
									couponGroupSelected = couponGroupSelected + coupon.nominalValue;
								}

								if ("single".equals(couponGroup.type)) {// 单选
									couponGroupSelected = coupon.nominalValue;
									requiredMinSelected = 0;// 单选前 每次清空总最低起投金额

									couponMap.clear();
									clearCouponSelected(mCouponItemLayout, couponGroup.type);
								}

								couponMap.put(
										String.valueOf(leftCouponLayout.getTag(R.id.tag_second)),
										lists.get(
												(Integer) leftCouponLayout.getTag(R.id.tag_fourth))
												.get((Integer) leftCouponLayout
														.getTag(R.id.tag_third)).couponId);

								couponUnSelectedStyle(leftCouponBg, leftCouponTitle, leftCouponNum,
										leftCouponUnit, leftCouponTime);
								leftCouponLayout.setTag(R.id.tag_first, "selected");
							}

							couponTipState();
							getAvailableAmountOfHmwallet();// 计算可获小惠钱包
						}
					});

				} else {
					final RelativeLayout rightCouponLayout = (RelativeLayout) viewConfirmCouponItem
							.findViewById(R.id.right_coupon_layout);
					rightCouponLayout.setVisibility(View.VISIBLE);

					final ImageView rightCouponBg = (ImageView) rightCouponLayout
							.findViewById(R.id.right_coupon_bg);

					final TextView rightCouponTitle = (TextView) rightCouponLayout
							.findViewById(R.id.right_coupon_title);
					rightCouponTitle.setText(coupon.channelTitle);

					final TextView rightCouponNum = (TextView) rightCouponLayout
							.findViewById(R.id.right_coupon_num);
					rightCouponNum.setText(Utils.amountConversionFormat(coupon.nominalValue));

					final TextView rightCouponUnit = (TextView) rightCouponLayout
							.findViewById(R.id.right_coupon_unit);

					final TextView rightCouponTime = (TextView) rightCouponLayout
							.findViewById(R.id.right_coupon_time);
					rightCouponTime.setText("过期时间：" + Utils.getDateString(coupon.expTime));

					rightCouponLayout.setTag(R.id.tag_first, "unSelected");
					rightCouponLayout.setTag(R.id.tag_second, "right"
							+ couponList.get(0).requiredMinInvestValue + j);
					rightCouponLayout.setTag(R.id.tag_third, j);
					rightCouponLayout.setTag(R.id.tag_fourth, i);

					if (coupon.requiredMinInvestValue > mMount) {
						rightCouponBg.setImageResource(R.drawable.que_img_hui);
						rightCouponTitle.setTextColor(getResources().getColor(R.color.white));
						rightCouponNum.setTextColor(getResources().getColor(R.color.white));
						rightCouponUnit.setTextColor(getResources().getColor(R.color.white));
						rightCouponTime.setTextColor(getResources().getColor(R.color.white));
					} else {
						rightCouponBg.setImageResource(R.drawable.que_img_bai);
						rightCouponTitle.setTextColor(getResources().getColor(R.color.text_orange));
						rightCouponNum.setTextColor(getResources().getColor(R.color.text_orange));
						rightCouponUnit.setTextColor(getResources().getColor(R.color.text_orange));
						rightCouponTime.setTextColor(getResources().getColor(R.color.text_orange));
					}

					rightCouponLayout.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							if (coupon.requiredMinInvestValue > mMount) {
								MyToast.showHMToast(TicketsWithCouponConfirmActivity.this, false,
										"起投金额最低" + coupon.requiredMinInvestValue + "可用！");
								return;
							}

							if ("selected".equals(String.valueOf(rightCouponLayout
									.getTag(R.id.tag_first)))) {

								couponGroupSelected = couponGroupSelected - coupon.nominalValue;

								requiredMinSelected = requiredMinSelected
										- coupon.requiredMinInvestValue;

								couponMap.remove(String.valueOf(rightCouponLayout
										.getTag(R.id.tag_second)));

								couponSelectedStyle(rightCouponBg, rightCouponTitle,
										rightCouponNum, rightCouponUnit, rightCouponTime);
								rightCouponLayout.setTag(R.id.tag_first, "unSelected");
							} else {
								/* 计算选择投资金额数目 start */
								requiredMinSelected = requiredMinSelected
										+ coupon.requiredMinInvestValue;

								if (mMount - requiredMinSelected < 0) {
									requiredMinSelected = requiredMinSelected
											- coupon.requiredMinInvestValue;

									MyToast.showHMToast(TicketsWithCouponConfirmActivity.this,
											false, "投资金额不足以可用！");
									return;
								}
								/* 计算选择投资金额数目 end */

								if ("multiple".equals(couponGroup.type)) {// 多选
									couponGroupSelected = couponGroupSelected + coupon.nominalValue;
								}

								if ("single".equals(couponGroup.type)) {// 单选
									couponGroupSelected = coupon.nominalValue;
									requiredMinSelected = 0;// 单选前 每次清空总最低起投金额

									couponMap.clear();
									clearCouponSelected(mCouponItemLayout, couponGroup.type);
								}

								couponMap.put(
										String.valueOf(rightCouponLayout.getTag(R.id.tag_second)),
										lists.get(
												(Integer) rightCouponLayout.getTag(R.id.tag_fourth))
												.get((Integer) rightCouponLayout
														.getTag(R.id.tag_third)).couponId);

								couponUnSelectedStyle(rightCouponBg, rightCouponTitle,
										rightCouponNum, rightCouponUnit, rightCouponTime);
								rightCouponLayout.setTag(R.id.tag_first, "selected");
							}

							couponTipState();
							getAvailableAmountOfHmwallet();// 计算可获小惠钱包

						}
					});

					mCouponItemLayout.addView(viewConfirmCouponItem);

					continue;
				}

				if ((j + 1) == couponList.size()) {
					mCouponItemLayout.addView(viewConfirmCouponItem);
				}

			}
		}

		if (couponGroupNum == 0) {
			mAssetsCoupons.setText("无可用");
		} else {
			mAssetsCoupons.setText(couponGroupNum + "张可用");
		}
	}

	/**
	 * 清楚单选
	 * 
	 * @param mCouponItemLayout
	 * @param type
	 */
	private void clearCouponSelected(TableLayout mCouponItemLayout, String type) {
		for (int i = 0; i < mCouponItemLayout.getChildCount(); i++) {
			if (mCouponItemLayout.getChildAt(i) instanceof TextView) {
				if (type.equals("single")) {
					continue;
				} else {
					return;
				}
			}

			RelativeLayout leftCouponLayout = (RelativeLayout) mCouponItemLayout.getChildAt(i)
					.findViewById(R.id.left_coupon_layout);
			if ("selected".equals(String.valueOf(leftCouponLayout.getTag(R.id.tag_first)))) {
				leftCouponLayout.setTag(R.id.tag_first, "unSelected");

				ImageView leftCouponBg = (ImageView) leftCouponLayout
						.findViewById(R.id.left_coupon_bg);
				TextView leftCouponTitle = (TextView) leftCouponLayout
						.findViewById(R.id.left_coupon_title);
				TextView leftCouponNum = (TextView) leftCouponLayout
						.findViewById(R.id.left_coupon_num);
				TextView leftCouponUnit = (TextView) leftCouponLayout
						.findViewById(R.id.left_coupon_unit);
				TextView leftCouponTime = (TextView) leftCouponLayout
						.findViewById(R.id.left_coupon_time);

				leftCouponBg.setImageResource(R.drawable.que_img_bai);
				leftCouponTitle.setTextColor(getResources().getColor(R.color.text_orange));
				leftCouponNum.setTextColor(getResources().getColor(R.color.text_orange));
				leftCouponUnit.setTextColor(getResources().getColor(R.color.text_orange));
				leftCouponTime.setTextColor(getResources().getColor(R.color.text_orange));
			}

			RelativeLayout rightCouponLayout = (RelativeLayout) mCouponItemLayout.getChildAt(i)
					.findViewById(R.id.right_coupon_layout);
			if ("selected".equals(String.valueOf(rightCouponLayout.getTag(R.id.tag_first)))) {
				rightCouponLayout.setTag(R.id.tag_first, "unSelected");

				ImageView rightCouponBg = (ImageView) rightCouponLayout
						.findViewById(R.id.right_coupon_bg);
				TextView rightCouponTitle = (TextView) rightCouponLayout
						.findViewById(R.id.right_coupon_title);
				TextView rightCouponNum = (TextView) rightCouponLayout
						.findViewById(R.id.right_coupon_num);
				TextView rightCouponUnit = (TextView) rightCouponLayout
						.findViewById(R.id.right_coupon_unit);
				TextView rightCouponTime = (TextView) rightCouponLayout
						.findViewById(R.id.right_coupon_time);

				rightCouponBg.setImageResource(R.drawable.que_img_bai);
				rightCouponTitle.setTextColor(getResources().getColor(R.color.text_orange));
				rightCouponNum.setTextColor(getResources().getColor(R.color.text_orange));
				rightCouponUnit.setTextColor(getResources().getColor(R.color.text_orange));
				rightCouponTime.setTextColor(getResources().getColor(R.color.text_orange));
			}
		}
	}

	// 选中样式
	private void couponSelectedStyle(ImageView couponBg, TextView couponTitle, TextView couponNum,
			TextView couponUnit, TextView couponTime) {
		couponBg.setImageResource(R.drawable.que_img_bai);
		couponTitle.setTextColor(getResources().getColor(R.color.text_orange));
		couponNum.setTextColor(getResources().getColor(R.color.text_orange));
		couponUnit.setTextColor(getResources().getColor(R.color.text_orange));
		couponTime.setTextColor(getResources().getColor(R.color.text_orange));
	}

	// 取消选中样式
	private void couponUnSelectedStyle(ImageView couponBg, TextView couponTitle,
			TextView couponNum, TextView couponUnit, TextView couponTime) {
		couponBg.setImageResource(R.drawable.que_img_chen);
		couponTitle.setTextColor(getResources().getColor(R.color.white));
		couponNum.setTextColor(getResources().getColor(R.color.white));
		couponUnit.setTextColor(getResources().getColor(R.color.white));
		couponTime.setTextColor(getResources().getColor(R.color.white));
	}

	// 现金券使用状态
	private void couponTipState() {
		if (couponGroupNum == 0) {
			mAssetsCoupons.setText("无可用");
		} else if (couponGroupNum > 0) {
			if (couponGroupSelected > 0) {
				mAssetsCoupons.setText(couponGroupNum + "张可用   已抵用"
						+ Utils.amountConversionFormat(couponGroupSelected) + "元");

				used.put("coupon", Utils.amountConversionFormat(couponGroupSelected));
			} else {
				used.remove("coupon");

				mAssetsCoupons.setText(couponGroupNum + "张可用");
			}
		}

		// caculateAccount();
	}

	/**
	 * 起投金额分组
	 * 
	 * @param coupons
	 * @return
	 */
	private List<List<Coupon>> getCouponGroup(List<Coupon> coupons) {
		List<List<Coupon>> list = new ArrayList<List<Coupon>>();
		// List<Coupon> tempList = null;
		List<Coupon> tempList = new ArrayList<Coupon>();

		int size = coupons.size();
		double temp = -1;
		for (int i = 0; i < size; i++) {
			Coupon cp = coupons.get(i);
			if (temp != cp.requiredMinInvestValue) {
				temp = cp.requiredMinInvestValue;
				tempList = new ArrayList<Coupon>();

				list.add(tempList);
				tempList.clear();
			}

			tempList.add(cp);
		}

		tempList = null;

		return list;
	}

	double h = 0.00;
	double c = 0.00;
	/**
	 * 计算实际金额
	 */
	private double caculateAccount() {
		double account = 0;
		double wallet = 0;
		double coupon = 0;

		if (used != null && used.size() > 0) {
			for (int i = 0; i < used.size(); i++) {
				boolean isCoupon = used.containsKey("coupon");
				boolean isWallet = used.containsKey("Wallet");

				if (isCoupon) {
					coupon = Double.parseDouble(used.get("coupon").toString());
				}

				if (isWallet) {
					wallet = Double.parseDouble(used.get("Wallet").toString());
				}
			}

			account = account + coupon + wallet;
			
			h = wallet;
			c = coupon;

			pay_amount.setText("已使用小惠钱包" + wallet + "元," + coupon + "元优惠券");
		} else {
			pay_amount.setText("");
			used.clear();
		}
		
		couponsAmount = coupon;

		pay_account.setText(mMount - account + "");

		return mMount - account;
	}

	/**
	 * 重置Coupons数据
	 */
	private void resetCouponsParams() {
		assets_coupons_more.setTag("off");
		assets_coupons_more.setImageResource(R.drawable.an_kg_off);

		// 清空选择样式
		// clearCouponSelected(mCouponItemLayout);
		mCouponItemLayout.removeAllViews();

		// 清空选择现金券
		used.remove("coupon");

		// 清空存储数据
		couponMap.clear();
		// 隐藏Table
		mCouponItemLayout.setVisibility(View.GONE);

		if (mCouponGroup != null && mCouponGroup.couponList.size() > 0) {
			mAssetsCoupons.setText(mCouponGroup.couponList.size() + "张可用");
		} else {
			mAssetsCoupons.setText("无可用");
		}
	}
	
	/**
	 * 设置提交按钮是否可点击
	 * @param ispress 是否可以点击
	 */
	private void setSubmitColor(boolean ispress){
		mConfirmInvestment.setFocusable(ispress);
		mConfirmInvestment.setClickable(ispress);
		
		if (ispress) {
			mConfirmInvestment.setBackgroundColor(getResources().getColor(R.color.radio_button_selected_color));
		} else {
			mConfirmInvestment.setBackgroundColor(getResources().getColor(R.color.more_line_bg));
		}
	}

	/**
	 * 获取可获小惠钱包
	 */
	private void getAvailableAmountOfHmwallet() {
		if (String.valueOf(xiao_hui_switch.getTag()).equals("on")) {
			availableAmountOfHmwallet(mMount,
					Double.parseDouble(String.valueOf(xiao_hui.getTag())), couponMap, mId);
		} else {
			availableAmountOfHmwallet(mMount, 0.0, couponMap, mId);
		}
	}

	/**
	 * 投资时计算可获得小惠钱包金额
	 */
	private void availableAmountOfHmwallet(double investAmount, double usingHmwalletAmount,
			HashMap<String, String> couponMap, String itemId) {
		RequestParams params = new RequestParams();
		params.addBodyParameter("itemId", itemId);
		params.addBodyParameter("usingHmwalletAmount", String.valueOf(usingHmwalletAmount));
		params.addBodyParameter("investAmount", String.valueOf(investAmount));

		if (String.valueOf(assets_coupons_more.getTag()).equals("on")) {
			if (couponMap.size() > 0) {
				for (HashMap.Entry<String, String> entry : couponMap.entrySet()) {
					// System.out.println(entry.getKey()+"--->"+entry.getValue());
					params.addBodyParameter("couponIds", entry.getValue());
				}
			}
		}

		onRequest(AVAILABLEAMOUNTOFHMWALLET, UrlConstant.AVAILABLEAMOUNTOFHMWALLET, HttpMethod.GET,
				params);
	}

	@Override
	protected void onResume() {
		super.onResume();

		RequestParams params = new RequestParams();
		params.addBodyParameter("itemId", getIntent().getStringExtra("id"));
		onRequest(CAPITAL, UrlConstant.CAPITALDETAIL, HttpMethod.GET, null);
		onRequest(BILL_TIME, UrlConstant.BILL_TIME, HttpMethod.POST, null);
		onRequest(GETCOUPONBYITEM, UrlConstant.GETCOUPONBYITEM, HttpMethod.GET, params);
	}

	@Override
	public void onPostSuccess(int postId, String result) {

		Gson gson = new Gson();
		switch (postId) {
		case CAPITAL:
			java.lang.reflect.Type type = new TypeToken<Capital>() {
			}.getType();
			mCapital = gson.fromJson(result, type);

			if (mCapital != null) {
				mInvestAmountEditText.setHint("可用金额 " + mCapital.availableBalance);
				mHMWallet = Double.parseDouble(String.valueOf(new BigDecimal(mCapital.hmWallet)));
			}
			xiao_hui.setText(mHMWallet + "");
			break;
		case SUBMIT:
			InvestmentSuccessDialog cd = new InvestmentSuccessDialog(this,
					R.style.calculatorDialog, "投资\n成功");
			cd.show();
			break;
		case BILL_TIME:
			java.lang.reflect.Type type1 = new TypeToken<InterestTime>() {
			}.getType();
			interestTime = gson.fromJson(result, type1);

			interestStart.setText(interestTime.interestStart);
			interestReceive.setText(interestTime.interestReceive);
			break;
		case AVAILABLE_AMOUNT:
			try {
				JSONObject jsonObject = new JSONObject(result);
				amount_expected.setText(jsonObject.getString("dailyIncome"));
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			// 计算可获积分
			RequestParams params2 = new RequestParams();
			params2.addBodyParameter("yield", amount_expected.getText().toString());
			params2.addBodyParameter("itemId", mId);
			onRequest(CONVER, UrlConstant.CONVER, HttpMethod.GET, params2);
			break;
		case GETCOUPONBYITEM:
			java.lang.reflect.Type type2 = new TypeToken<CouponGroup>() {
			}.getType();
			mCouponGroup = gson.fromJson(result, type2);

			if (mCouponGroup != null && mCouponGroup.couponList.size() > 0) {
				Collections.sort(mCouponGroup.couponList);
				mAssetsCoupons.setText(mCouponGroup.couponList.size() + " 张可用");
			} else {
				mAssetsCoupons.setText("无可用");
			}
			break;
		case CONVER:// 积分换算
			java.lang.reflect.Type type3 = new TypeToken<Score>() {
			}.getType();
			Score score = gson.fromJson(result, type3);
			if (score.extraScore > 0) {
				amount_score.setText(Utils.amountConversionFormat(score.score) + "+"
						+ Utils.amountConversionFormat(score.extraScore));
			} else {
				amount_score.setText(Utils.amountConversionFormat(score.score));
			}
			break;
		case AVAILABLEAMOUNTOFHMWALLET:
//			mConfirmInvestment.setEnabled(true);
			setSubmitColor(true);

			java.lang.reflect.Type type4 = new TypeToken<AvailableAmountOfHmwallet>() {
			}.getType();
			AvailableAmountOfHmwallet availableAmountOfHmwallet = gson.fromJson(result, type4);

			enable_amount.setText(Utils
					.amountConversionFormat(availableAmountOfHmwallet.availableAmountOfHmwallet));

			caculateAccount();
			break;
		}

	}

	@Override
	public void onPostFailure(int postId, String msg) {
		switch (postId) {
		case SUBMIT:
			setParams();
			break;

		default:
			break;
		}
	}

	@Override
	protected void setParams() {

		home_title.setOnTouchListener(touch);
		home_title_txt.setText("确认投资");
		mInvestAmountEditText.addTextChangedListener(BenefitCalculations);
		xiao_hui_switch.setTag("off");
		assets_coupons_more.setTag("off");
//		mConfirmInvestment.setEnabled(false);
		mConfirmInvestment.setText(R.string.confirm_investment);
		// 重置现金券选项
		resetCouponsParams();
		// 设置点击按钮颜色
		setSubmitColor(false);

		personal_name.setText(AppBasic.realName);
		personal_tel.setText(Utils.hidePhone(PreferencesUtils.getString(this,
				PreferencesUtils.USER_PHONE)));

		mBaseAmount = getIntent().getStringExtra("baseAmount");
		mMinInvestAmount = getIntent().getStringExtra("minInvestAmount");

		investment_name.setText(getIntent().getStringExtra("name"));
		investment_rate.setText(getIntent().getStringExtra("rate") + "%");

		mId = getIntent().getStringExtra("id");
		if (getIntent().getStringExtra("time").equals("1")) {
			investment_time.setText("活期");
		} else if (getIntent().getStringExtra("time").equals("30")) {
			investment_time.setText("锁定期：30天");
		} else {
			investment_time.setText(getIntent().getStringExtra("time")
					+ Utils.periodConversion(getIntent().getStringExtra("timeUnit")));
		}

	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {

	}

	protected static long lastClickTime;

	/** 防止在短时间重复点击 **/
	public static boolean isFastDoubleClick() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		if (0 < timeD && timeD < 800) {
			return true;
		}
		lastClickTime = time;
		return false;
	}

	/**
	 * 收益计算
	 */

	long oldTime = 0;
	long newTime = 0;

	ArrayList<Timer> timerList = new ArrayList<Timer>();
	@SuppressLint("HandlerLeak")
	final Handler verificationHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 0:
				amount_expected.setText("0");
				enable_amount.setText("0");
				amount_score.setText("0");
				mMount = 0.0;

				resetCouponsParams();

				pay_account.setText("0");
				xiao_hui_switch.setTag("off");
				xiao_hui_switch.setImageResource(R.drawable.an_kg_off);

				xiao_hui.setText(mHMWallet + "");

				break;
			case 1:
				MyToast.showHMToast(TicketsWithCouponConfirmActivity.this, false, "投资金额格式有误");
				break;
			case 2:
				MyToast.showHMToast(TicketsWithCouponConfirmActivity.this, false, "项目最低"
						+ mMinInvestAmount + "元起投");
				break;
			case 3:
				MyToast.showHMToast(TicketsWithCouponConfirmActivity.this, false, "投资金额必须为"
						+ mBaseAmount + "的整数倍");
				break;
			case 4:
				final NormalDialog cd = new NormalDialog(TicketsWithCouponConfirmActivity.this,
						R.style.calculatorDialog, new NormalDialogListener() {
							@Override
							public void ok() {
								startActivity(new Intent(TicketsWithCouponConfirmActivity.this,
										RechargeActivity.class));
								AppBasic.getInstance().finishCurrentActivity();
							}

							@Override
							public void cancle() {

							}

							@Override
							public void closed() {

							}

						},
						TicketsWithCouponConfirmActivity.this.getString(R.string.investment_tips),
						TicketsWithCouponConfirmActivity.this
								.getString(R.string.investment_tips_content), "充值", "");
				cd.show();
				break;
			case 5:
//				amount_expected.setText(msg.obj == null ? "0" : String.valueOf(msg.obj));

				//计算预期收益
				RequestParams params3 = new RequestParams();
				params3.addBodyParameter("investAmount", String.valueOf(msg.obj));
				params3.addBodyParameter("itemId", getIntent().getStringExtra("id"));
				params3.addBodyParameter("itemRateId", getIntent().getStringExtra("itemRateId"));
				onRequest(AVAILABLE_AMOUNT, UrlConstant.AVAILABLE_AMOUNT, HttpMethod.POST, params3);

				break;
			case 6:
				mMount = Double.parseDouble(String.valueOf(msg.obj));

				// 现金券清除选择
				if (String.valueOf(assets_coupons_more.getTag()).equals("on")) {
					resetCouponsParams();
				}

				// 小惠钱包清除选择
				if (!TextUtils.isEmpty(AppBasic.app.hmwalletUsablePersent)) {

					BigDecimal mount = new BigDecimal(String.valueOf(mMount));
					BigDecimal hmWallet = new BigDecimal(String.valueOf(mCapital.hmWallet));
					BigDecimal hmwalletUsablePersent = new BigDecimal(
							(AppBasic.app.hmwalletUsablePersent));

					BigDecimal hmWalletEnable = Utils.scale(mount.multiply(hmwalletUsablePersent)
							.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN));

					int r = hmWalletEnable.compareTo(hmWallet);

					if (mCapital.hmWallet == 0) {
						xiao_hui_switch.setImageResource(R.drawable.an_kg_off);
						xiao_hui_switch.setTag("off");

						xiao_hui.setText(mCapital.hmWallet + "");
						xiao_hui.setTag("0");
					} else if (r == 1) {
						xiao_hui_switch.setImageResource(R.drawable.an_kg_off);
						xiao_hui_switch.setTag("off");

						xiao_hui.setText(Utils.amountConversionFormat(Double.parseDouble(String
								.valueOf(hmWallet))));
						xiao_hui.setTag(String.valueOf(hmWallet));
					} else {
						xiao_hui_switch.setImageResource(R.drawable.an_kg_off);
						xiao_hui_switch.setTag("off");

						// mHMWalletEnable =
						// Double.parseDouble(String.valueOf(hmWalletEnable));
						xiao_hui.setText(Utils.amountConversionFormat(Double.parseDouble(String
								.valueOf(hmWallet))));
						xiao_hui.setTag(String.valueOf(hmWalletEnable));
					}

				}

				// 设置实际支付
				pay_account.setText(mMount + "");

				getAvailableAmountOfHmwallet();// 计算可获小惠钱包

				break;
			case 7:
				String rate = getIntent().getStringExtra("rate");
				rate = rate.contains("%") ? rate.replace("%", "") : rate;
				
				final ConfirmInvestmentDialog cd1 = new ConfirmInvestmentDialog(TicketsWithCouponConfirmActivity.this,
						R.style.calculatorDialog, new NormalDialogListener() {
					@Override
					public void ok() {

						RequestParams params = new RequestParams();
						params.addBodyParameter("itemId", mId);
						params.addBodyParameter("investAmount", String.valueOf(mMount));
						params.addBodyParameter("itemRateId", getIntent().getStringExtra("itemRateId"));

						if (String.valueOf(xiao_hui_switch.getTag()).equals("on")) {
							params.addBodyParameter("useWalletAmount", String.valueOf(xiao_hui.getTag()));
						} else {
							params.addBodyParameter("useWalletAmount", String.valueOf(0));
						}

						StringBuilder builder = new StringBuilder();
						if (String.valueOf(assets_coupons_more.getTag()).equals("on")) {
							if (couponMap.size() > 0) {
								for (HashMap.Entry<String, String> entry : couponMap.entrySet()) {
									System.out.println(entry.getKey() + "--->" + entry.getValue());
									params.addBodyParameter("couponIds", entry.getValue());
									builder.append(entry.getValue()+",");
								}
							}
						}
						
						params.addBodyParameter("couponsAmount", String.valueOf(couponsAmount));

//						mConfirmInvestment.setEnabled(false);
						mConfirmInvestment.setText("提交中...");
						setSubmitColor(false);

						onRequest(SUBMIT, UrlConstant.BILL_INVESTMENT, HttpMethod.POST, params);
					}

					@Override
					public void cancle() {

					}

					@Override
					public void closed() {

					}

				},
				getIntent().getStringExtra("name"),
				rate + "%",
				getIntent().getStringExtra("time")+Utils.periodConversion(getIntent().getStringExtra("timeUnit")),
				mInvestAmountEditText.getText().toString().trim(),
				h+"", 
				c+"",
				pay_account.getText().toString().trim(),
				"确认投资",
				"取消投资");
				cd1.show();
				break;
			default:

				break;
			}
			super.handleMessage(msg);
		}
	};

	private TextWatcher BenefitCalculations = new TextWatcher() {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {

		}

		@Override
		public void afterTextChanged(final Editable s) {
			pay_amount.setText("");
			used.clear();

			for (Timer _timer : timerList) {
				_timer.cancel();
			}

			Timer timer = new Timer();
			timerList.add(timer);

			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					Message message = new Message();

					if (TextUtils.isEmpty(s.toString().trim())) {
						message.what = 0;
						verificationHandler.sendMessage(message);

						return;
					}

					try {
						Double.parseDouble(s.toString().trim());
					} catch (Exception e) {
						message.what = 1;
						verificationHandler.sendMessage(message);
						return;
					}

					try {
						double minInvestAmount = Double.parseDouble(mMinInvestAmount);
						double investAmount = Double.parseDouble(s.toString().trim());

						if (investAmount < minInvestAmount) {
							message.what = 2;
							verificationHandler.sendMessage(message);
							return;
						}

						double baseAmount = Double.parseDouble(mBaseAmount);

						if (investAmount % baseAmount != 0) {
							message.what = 3;
							verificationHandler.sendMessage(message);
							return;
						}

						if (mCapital != null && investAmount > mCapital.availableBalance) {
							message.what = 4;
							verificationHandler.sendMessage(message);
							return;
						}
					} catch (Exception e) {
						return;
					}

					message.what = 5;
//					message.obj = calculation(s.toString(), getIntent().getStringExtra("time"),
//							getIntent().getStringExtra("timeUnit"),
//							getIntent().getStringExtra("rate"));
					message.obj = s.toString();
					verificationHandler.sendMessage(message);

					Message message2 = new Message();
					message2.what = 6;
					message2.obj = s.toString();
					verificationHandler.sendMessage(message2);

					System.out.println(s + "-time-" + System.currentTimeMillis());

				}
			}, 1000);
		}
	};

	private String calculation(String amount, String time, String timeUnit, String rate) {
		try {
			BigDecimal t = new BigDecimal(time);
			BigDecimal investAmount = new BigDecimal((amount.trim()));
			BigDecimal r = new BigDecimal((rate));

			if ("Year".equals(timeUnit)) {
				return (String.valueOf(Utils.scale(investAmount.multiply(r)
						.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN).multiply(t))));
			} else if ("Month".equals(timeUnit)) {
				return (String.valueOf(Utils.scale(investAmount.multiply(r)
						.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN)
						.divide(new BigDecimal("12"), 2, BigDecimal.ROUND_DOWN).multiply(t))));
			} else if ("Day".equals(timeUnit)) {
				return (String.valueOf(Utils.scale(investAmount.multiply(r)
						.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN)
						.divide(new BigDecimal("365"), 2, BigDecimal.ROUND_DOWN).multiply(t))));
			}

		} catch (Exception e) {

		}

		return null;
	}
}
